#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int head_create(NODE_T **head)
{
    NODE_T *hp = NULL;

    // 申请空间
    hp = malloc(sizeof(NODE_T));
    if (hp == NULL)
    {
        perror("malloc fail...");
        goto err0;
    }
    memset(hp, 0, sizeof(NODE_T));

    *head = hp;
    return 0;

err0:
    return -1;
}

int head_insert(NODE_T *head, int num)
{
    NODE_T *new_node = NULL;
    NODE_T *tmp = head;

    // 容错判断
    if (NULL == head)
    {
        perror("head = null??");
        goto err0;
    }

    // 申请空间
    new_node = malloc(sizeof(NODE_T));
    if (NULL == new_node)
    {
        perror("malloc fail...");
        goto err0;
    }
    memset(new_node, 0, sizeof(NODE_T));

    // 数据写入
    new_node->num = num;

    // 链表头部插入
    new_node->next = tmp->next;
    tmp->next = new_node;



    return 0;

err0:
    return -1;
}



int list_traverse(NODE_T *head)
{
    // 容错判断
    if (head == NULL)
    {
        perror("head = null?");
        goto err0;
    }

    head = head->next;

    // 遍历
    while (head != NULL)
    {
        printf("%d\n", head->num);
        head = head->next;
    }


    return 0;

err0:
    return -1;
}

int list_destroy(NODE_T *head)
{
    // 容错判断
    if (head == NULL)
    {
        perror("head=null?");
        return -1;
    }

    NODE_T *tmp = head->next;
    NODE_T *save = NULL;

    

    while (tmp != NULL)
    {
        save = tmp->next;
        free(tmp);
        tmp = save;
    }
    return 0;   
}
